//
//  TLUnlockSSVipViewViewController.m
//  WXReader
//
//  Created by huaya on 2025/9/6.
//  Copyright © 2025 Andrew. All rights reserved.
//

#import "TLRewardsViewController.h"
#import "TLRewardsHeaderView.h"
#import "TLRewardsHeaderTableViewCell.h"
#import "TLRewardsTableViewCell.h"

#import "TLTaskModel.h"
#import "TLSignTaskModel.h"
#import "TLSignTaskDetailModel.h"

#import "TLRewardsSuccessView.h"

#import "TLMyBonusTipsView.h"

@interface TLRewardsViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIView *titleView;
@property (nonatomic, strong) UIView *navView;
@property (nonatomic, strong) UILabel *navTitleLab;
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UIButton *messageBtn;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) TLRewardsHeaderView *headerView;

@property (nonatomic, strong) NSMutableArray<TLTaskModel *> *specialTasks;
@property (nonatomic, strong) NSMutableArray<TLTaskModel *> *cycleTasks;
@property (nonatomic, strong) TLSignTaskModel *signTaskVO;

@property (nonatomic, strong) TLMyBonusTipsView *tipsView;

@property (nonatomic, strong) NSString *tipsStr;

@end

@implementation TLRewardsViewController

- (NSMutableArray<TLTaskModel *> *)cycleTasks{
    if (!_cycleTasks) {
        _cycleTasks = [NSMutableArray new];
    }
    return _cycleTasks;
}
- (NSMutableArray<TLTaskModel *> *)specialTasks{
    if (!_specialTasks) {
        _specialTasks = [NSMutableArray new];
    }
    return _specialTasks;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self netWork];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addGradientBackground];
    
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.navView];
    
    
}
- (UIView *)navView{
    if (!_navView) {
        _navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, PUB_NAVBAR_HEIGHT)];
        [_navView setBackgroundColor:[UIColor clearColor]];
        _backBtn = [[UIButton alloc] initWithFrame:CGRectMake(6, PUB_NAVBAR_HEIGHT - 28 - 6, 28, 28)];
        [_backBtn setImage:[UIImage imageNamed:@"tzxqy_fh"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navView addSubview:_backBtn];
        
        _navTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_backBtn.frame)+10, PUB_NAVBAR_HEIGHT - 28 - 6, kScreenWidth-2*(CGRectGetMaxX(_backBtn.frame)+10), 28)];
        _navTitleLab.text = WXLocalizedString(@"任务中心");
        _navTitleLab.textColor = [UIColor hex_333333];
        _navTitleLab.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
        _navTitleLab.textAlignment = NSTextAlignmentCenter;
        [_navView addSubview:_navTitleLab];
        
        _messageBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-18-16-16, PUB_NAVBAR_HEIGHT - 28 - 6, 28, 28)];
        [_messageBtn setImage:[UIImage imageNamed:@"wdzb_bz"] forState:UIControlStateNormal];
        [_messageBtn addTarget:self action:@selector(msgAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navView addSubview:_messageBtn];
        
    }
    return _navView;
}

- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)msgAction{
//    
    self.tipsView = [TLMyBonusTipsView createView];
    
    [self.tipsView showInView:self.view andContent:self.tipsStr];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        if (self.cycleTasks.count>0) {
            return self.cycleTasks.count+1;
        }
    }else{
        if (self.specialTasks.count>0) {
            return self.specialTasks.count+1;
        }
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        return 50;
    }else{
        return 126;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        
        TLRewardsHeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLRewardsHeaderTableViewCell"];

        return cell;
    }else{
        TLRewardsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLRewardsTableViewCell"];
        
        if (indexPath.section==0) {
            
            if ((indexPath.row-1) < self.cycleTasks.count) {
                
                cell.taskModel = self.cycleTasks[(indexPath.row-1)];
            }
            
            if (indexPath.row == self.cycleTasks.count) {
                [cell setBottomCorners];
            }else{
                [cell setDefultCorners];
            }
            
        }else if (indexPath.section==1){
            
            if ((indexPath.row-1) < self.specialTasks.count) {
                
                cell.taskModel = self.specialTasks[(indexPath.row-1)];
            }
            
            if (indexPath.row == self.specialTasks.count) {
                [cell setBottomCorners];
            }else{
                [cell setDefultCorners];
            }
        }
        
        MJWeakSelf
        
        cell.checkInBlock = ^(NSString * _Nonnull bonus, NSString * _Nonnull validStr) {
            
            TLRewardsSuccessView *sv = [TLRewardsSuccessView createView];
            sv.reloadDataBlock = ^{
                [weakSelf netWork];
            };
            [sv showInView:weakSelf.view andBonus:[NSNumber numberWithString:bonus] andValid:validStr];
            
        };
        
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (UITableView *)tableView{
    if (!_tableView) {
        UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width,MK_SCREEN_SAVE_BOTTOM_HEIGHT)];
        footView.backgroundColor = UIColor.clearColor;
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.navView.frame), kScreenWidth, kScreenHeight-CGRectGetMaxY(self.navView.frame)) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = footView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = YES;
        
        if (@available(iOS 15.0, *)) {
            self.tableView.sectionHeaderTopPadding = 0;
        }
        
        [_tableView registerNib:[UINib nibWithNibName:@"TLRewardsTableViewCell" bundle:nil] forCellReuseIdentifier:@"TLRewardsTableViewCell"];
        
        [_tableView registerNib:[UINib nibWithNibName:@"TLRewardsHeaderTableViewCell" bundle:nil] forCellReuseIdentifier:@"TLRewardsHeaderTableViewCell"];
        
        self.headerView = [TLRewardsHeaderView createView];
        MJWeakSelf
        _headerView.checkInBlock = ^(NSNumber *num) {
            
            TLRewardsSuccessView *sv = [TLRewardsSuccessView createView];
            sv.reloadDataBlock = ^{
                [weakSelf netWork];
            };
            [sv showInView:weakSelf.view andBonus:num
                  andValid:weakSelf.signTaskVO.expireDays];
            
        };
        
        _tableView.tableHeaderView = self.headerView;
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(netWork)];
        header.lastUpdatedTimeLabel.hidden = YES;
        _tableView.mj_header = header;
        
    }
    return _tableView;
}
- (void)netWork{
    
    UIView *loadinView = [TL_TopAlertManager showLoading:self.view];
    [APIManager sendGetRequest:[APIURLManager getTaskList] parameters:@{} model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        [loadinView removeFromSuperview];
        
        if (success) {
            
            if (requestModel.data[@"signTaskVO"]) {
                
                self.signTaskVO = [TLSignTaskModel mj_objectWithKeyValues:requestModel.data[@"signTaskVO"]];
            }
            
            if (requestModel.data[@"specialTasks"]) {
                
                self.specialTasks = [TLTaskModel mj_objectArrayWithKeyValuesArray:requestModel.data[@"specialTasks"]];
            }
            
            if (requestModel.data[@"cycleTasks"]) {
                
                self.cycleTasks = [TLTaskModel mj_objectArrayWithKeyValuesArray:requestModel.data[@"cycleTasks"]];
            }
            
//            self.headerView.signTaskVO = self.signTaskVO;
            
            self.tipsStr = requestModel.data[@"taskDescription"];
            
            [self.tableView reloadData];
            
            [self getUserData];
        }else{
            
            [self.tableView.mj_header endRefreshing];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        
        [loadinView removeFromSuperview];
        [self.tableView.mj_header endRefreshing];
    }];
    
}
- (void)getUserData{
    
    MK_WEAK_SELF
    
    UIView *loadinView = [TL_TopAlertManager showLoading:self.view];
    
    [APIManager sendGetRequest:[APIURLManager getUserInfo] parameters:@{} model:TL_UserInfoModel.class success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        [loadinView removeFromSuperview];
        if (success) {
            NSLog(@"%@",requestModel);
            
            TL_UserInfoModel *usermodel = [TL_UserInfoModel mj_objectWithKeyValues:requestModel.data[@"userInfo"]];

            NSDictionary *userDataDict = [usermodel mj_keyValues];
            
            [[NSUserDefaults standardUserDefaults] setObject:userDataDict forKey:@"UserInfoModelDict"];
            
            TL_UserInfoManager.updateWithDict(requestModel.data[@"userInfo"]);
            
            [self.tableView reloadData];
            self.headerView.signTaskVO = self.signTaskVO;
        } else {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg ?: WXLocalizedString(@"请求失败")];
            if (requestModel.code == 302) {
                [TL_UserInfoManager logout];
            }
        }
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"%@",error);
        [loadinView removeFromSuperview];
        [self.tableView.mj_header endRefreshing];
    }];
}
@end
